package com.sdkj.fixed.asset.login.config.mybatis;


import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;

import com.sdkj.fixed.asset.common.database.DatabaseType;
import com.sdkj.fixed.asset.common.database.DynamicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * springboot集成mybatis的基本入口
 * 1）创建数据源(如果采用的是默认的tomcat-jdbc数据源，则不需要)
 * 2）创建SqlSessionFactory 3）配置事务管理器，除非需要使用事务，否则不用配置
 */
@Configuration // 该注解类似于spring配置文件
public class MyBatisConfig{

    @Value("${druid.initialSize}")
    private String initialSize;
    @Value("${druid.minIdle}")
    private String minIdle;
    @Value("${druid.maxActive}")
    private String maxActive;
    @Value("${druid.maxWait}")
    private String maxWait;
    @Value("${druid.timeBetweenEvictionRunsMillis}")
    private String timeBetweenEvictionRunsMillis;
    @Value("${druid.minEvictableIdleTimeMillis}")
    private String minEvictableIdleTimeMillis;
    @Value("${druid.validationQuery}")
    private String validationQuery;
    @Value("${druid.testWhileIdle}")
    private String testWhileIdle;
    @Value("${druid.testOnBorrow}")
    private String testOnBorrow;
    @Value("${druid.testOnReturn}")
    private String testOnReturn;
    @Value("${druid.poolPreparedStatements}")
    private String poolPreparedStatements;
    @Value("${druid.maxPoolPreparedStatementPerConnectionSize}")
    private String maxPoolPreparedStatementPerConnectionSize;
    @Value("${druid.filters}")
    private String filters;

    @Value("${mybatis.type-aliases-package}")
    private String typeAliasesPackage;
    @Value("${mybatis.mapper-locations}")
    private String locations;
    @Value("${mybatis.mapper-configLocation}")
    private String configLocation;
    @Value("${datasource.driverClassName}")
    private String driverClassName;
    @Value("${datasource.url}")
    private String url;
    @Value("${datasource.username}")
    private String username;
    @Value("${datasource.password}")
    private String password;





    @Bean
    @Primary
    public DynamicDataSource dataSource() throws Exception {
        Map<Object, Object> targetDataSources = new HashMap<>();

        Properties props = new Properties();

        props.put("initialSize",initialSize);
        props.put("minIdle",minIdle);
        props.put("maxActive",maxActive);
        props.put("maxWait",maxWait);
        props.put("timeBetweenEvictionRunsMillis",timeBetweenEvictionRunsMillis);
        props.put("minEvictableIdleTimeMillis",minEvictableIdleTimeMillis);
        props.put("validationQuery",validationQuery);
        props.put("testWhileIdle",testWhileIdle);
        props.put("testOnBorrow",testOnBorrow);
        props.put("testOnReturn", testOnReturn);
        props.put("poolPreparedStatements",poolPreparedStatements);
        props.put("maxPoolPreparedStatementPerConnectionSize",maxPoolPreparedStatementPerConnectionSize);
        props.put("filters",filters);


        props.put("driverClassName",driverClassName);
        props.put("url",url);
        props.put("username",username);
        props.put("password",password);
        DataSource ds1 = DruidDataSourceFactory.createDataSource(props);
        targetDataSources.put(DatabaseType.database1, ds1);
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
        dataSource.setDefaultTargetDataSource(ds1);

        // 默认的datasource设置为test2DataSource
        return dataSource;
    }


    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(ds);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        sessionFactoryBean.setMapperLocations(resolver.getResources(locations));
        sessionFactoryBean.setConfigLocation(resolver.getResource(configLocation));
        return sessionFactoryBean.getObject();
    }



    /**
     * 配置事务管理器
     */
    @Bean
    public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
        return new DataSourceTransactionManager(dataSource);
    }


}